<script lang="jsx">
import { defineComponent, defineAsyncComponent, h } from 'vue'
import { enumRemoteMethod, doSelectChange } from '../AutoGrid/tool'
import MetaUpload from './Upload.vue'
import { infiniteScroll } from '@/modules/utils/directives'
import { inputQuerySearch } from '../utils/table.ts'

const modules = import.meta.glob('../../views/**/*.{vue,tsx}')

export default defineComponent({
  name: 'CellRender',
  components: { MetaUpload },
  directives: {
    infiniteScroll
  },
  props: {
    row: {
      type: Object,
      default: () => ({})
    },
    col: {
      type: Object,
      default: () => ({})
    },
    meta: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    console.log('===== EditRender')
    // const pinyinEngineData = {}
    // const initAutocomplete = (fields) => {
    //   const reqFields = fields.filter((col) => ['string'].includes(col.type) && col.pinyin_search)
    //   reqFields.forEach((col) => {
    //     pinyinEngineData[col.key] = new PinyinEngine(col.values || [], ['value'])
    //   })
    // }
    const row = props.row
    const col = props.col
    if (props.meta) {
      return () => {
        switch (col.type) {
          case 'string':
            if (col.pinyin_search || col.source)
              return (
                <el-autocomplete
                  placeholder={col.placeholder || '请输入'}
                  clearable={true}
                  value-key="name"
                  {...col.autocomplete}
                  v-model={row[col.key]}
                  fetch-suggestions={(qs, cb) => inputQuerySearch(qs, cb, col, row)}
                />
              )
            else return <el-input v-model={row[col.key]} />
          case 'text':
          case 'textarea':
            return <el-input type="textarea" rows={col.rows || 2} v-model={row[col.key]} />
          case 'number':
            return <el-input type="number" v-model={row[col.key]} />
          case 'int':
            return <el-input type="number" v-model={row[col.key]} />
          case 'float':
            return <el-input type="number" v-model={row[col.key]} />
          case 'password':
            return <el-input type="password" show-password v-model={row[col.key]} />
          case 'enum':
            return (
              <el-select
                filterable
                clearable
                teleported={false}
                placeholder="请选择"
                v-infinite-scroll={{ col, row, emit }}
                {...col.props}
                {...(col.source
                  ? {
                      remote: true,
                      'remote-show-suffix': true,
                      'remote-method': (qs) => enumRemoteMethod(qs, col, row)
                    }
                  : {})}
                v-model={row[col.key]}
                onClear={() => (row[col.key] = '')} // 点击clear事件，clear恢复默认值
                {...(col.watch || col?.source?.results
                  ? {
                      onChange: (val) => {
                        doSelectChange(row, col, 'change', val)
                      }
                    }
                  : {})}
                v-slots={
                  col.source?.showHeaders?.length
                    ? {
                        header: () => (
                          <div
                            style={`display: grid; grid-template-columns: repeat(${
                              col.source?.showHeaders?.length || 1
                            }, 1fr); padding: 0 20px 0 10px`}
                          >
                            {(col.source?.showHeaders || []).map((item, i) => (
                              <div key={i} style={{ 'text-align': i > 0 ? 'right' : 'left' }}>
                                {item}
                              </div>
                            ))}
                          </div>
                        )
                      }
                    : {}
                }
              >
                {col.values?.map((val) =>
                  typeof val === 'object' ? (
                    <el-option
                      key={val[col?.source?.keyField || 'key']}
                      label={val[col?.source?.nameField || 'name']}
                      value={val[col?.source?.keyField || 'key']}
                    >
                      {col.source?.showFields ? (
                        <div
                          style={`display: grid; grid-template-columns: repeat(${
                            col.source?.showHeaders?.length >= col.source?.showFields?.length
                              ? col.source?.showHeaders?.length
                              : col.source?.showFields?.length + 1
                          }, 1fr)`}
                        >
                          {!col.source?.showHeaders?.length ||
                          col.source?.showFields?.length < col.source?.showHeaders?.length ? (
                            <span style="text-align: left">
                              {val[col.source.nameField || 'name']}
                            </span>
                          ) : undefined}
                          {col.source.showFields.map((field, i) => (
                            <span
                              key={field}
                              style={`${
                                col.source?.showFields?.length >= col.source?.showHeaders?.length &&
                                i < 1
                                  ? 'text-align: left'
                                  : 'text-align: right; margin-left: 10px'
                              }; color: var(--el-text-color-secondary); font-size: 13px;`}
                            >
                              {val[field]}
                            </span>
                          ))}
                        </div>
                      ) : undefined}
                    </el-option>
                  ) : (
                    <el-option key={val} label={val} value={val} />
                  )
                )}
              </el-select>
            )
          case 'list':
            if (typeof row[col.key] === 'string' && /\[.+\]/.test(row[col.key])) {
              row[col.key] = JSON.parse(row[col.key])
            }
            return (
              <el-select
                filterable
                clearable
                allow-create
                multiple
                collapse-tags
                teleported={false}
                placeholder="请选择"
                v-infinite-scroll={{ col, row, emit }}
                {...col.props}
                {...(col.source
                  ? {
                      remote: true,
                      'remote-show-suffix': true,
                      'remote-method': (qs) => enumRemoteMethod(qs, col, row)
                    }
                  : {})}
                v-model={row[col.key]}
                onClear={() => (row[col.key] = '')} // 点击clear事件，clear恢复默认值
                {...(col.watch || col?.source?.results
                  ? {
                      onChange: (val) => {
                        doSelectChange(row, col, 'change', val)
                      }
                    }
                  : {})}
                v-slots={
                  col.source?.showHeaders?.length
                    ? {
                        header: () => (
                          <div
                            style={`display: grid; grid-template-columns: repeat(${
                              col.source?.showHeaders?.length || 1
                            }, 1fr); padding: 0 20px 0 10px`}
                          >
                            {(col.source?.showHeaders || []).map((item, i) => (
                              <div key={i} style={{ 'text-align': i > 0 ? 'right' : 'left' }}>
                                {item}
                              </div>
                            ))}
                          </div>
                        )
                      }
                    : {}
                }
              >
                {col.values?.map((val) =>
                  typeof val === 'object' ? (
                    <el-option
                      key={val[col?.source?.keyField || 'key']}
                      label={val[col?.source?.nameField || 'name']}
                      value={val[col?.source?.keyField || 'key']}
                    >
                      {col.source?.showFields ? (
                        <div
                          style={`display: grid; grid-template-columns: repeat(${
                            col.source?.showHeaders?.length >= col.source?.showFields?.length
                              ? col.source?.showHeaders?.length
                              : col.source?.showFields?.length + 1
                          }, 1fr)`}
                        >
                          {!col.source?.showHeaders?.length ||
                          col.source?.showFields?.length < col.source?.showHeaders?.length ? (
                            <span style="text-align: left">
                              {val[col.source.nameField || 'name']}
                            </span>
                          ) : undefined}
                          {col.source.showFields.map((field, i) => (
                            <span
                              key={field}
                              style={`${
                                col.source?.showFields?.length >= col.source?.showHeaders?.length &&
                                i < 1
                                  ? 'text-align: left'
                                  : 'text-align: right; margin-left: 10px'
                              }; color: var(--el-text-color-secondary); font-size: 13px;`}
                            >
                              {val[field]}
                            </span>
                          ))}
                        </div>
                      ) : undefined}
                    </el-option>
                  ) : (
                    <el-option key={val} label={val} value={val} />
                  )
                )}
              </el-select>
            )
          case 'range':
            return <el-slider v-model={row[col.key]} min={col.range[0]} max={col.range[1]} />
          case 'datetime':
            return (
              <el-date-picker
                v-model={row[col.key]}
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              />
            )
          case 'bool':
            return <el-checkbox v-model={row[col.key]} />
          case 'file':
            return <meta-upload {...col.props} v-model={row[col.key]} meta={col} />
          case 'fileset':
            return <meta-upload {...col.props} v-model={row[col.key]} meta={col} multiple />
          case 'component':
            // 如果配置了自定义组件，使用自定义组件渲染
            const moduleLoader = modules[`../../views/${col.component.module}.vue`]
            if (moduleLoader) {
              const MyAsyncComponent = defineAsyncComponent({
                loader: () => moduleLoader()
              })
              // 渲染异步组件，并传递默认插槽内容
              return h(MyAsyncComponent, {
                key: row.id,
                data: row,
                col,
                meta: props.meta,
                mode: 'edit'
              })
            }
          default:
            return <>{row[col.key]}</>
        }
      }
    }
    return {}
  }
})
</script>
<style lang="less">
.vxe-select--panel.is--transfer {
  z-index: 3001 !important;
}
.vxe-table {
  .vxe-body--column.preview-thumbnail {
    & > .vxe-cell {
      height: 100%;
    }
    .el-link {
      width: 100%;
      height: 100%;
      .el-link__inner {
        width: 100%;
        height: 100%;
      }
      img {
        width: auto;
      }
    }
  }
}
</style>
